package com.husd.framework.nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author hushengdong@gome.com.cn
 * @date 2022/1/22 9:34 下午
 */
public class GatheringExample {

    public static void main(String[] args) throws IOException {

        String path = "/tmp/a.txt";
        File f = new File(path);
        f.delete();
        if (!f.exists()) {
            f.createNewFile();
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(f, "rw");
        FileChannel channel = randomAccessFile.getChannel();

        ByteBuffer header = ByteBuffer.allocate(3 * 4);
        header.clear();
        header.putInt(10);
        header.putInt(10);
        header.putInt(10);
        header.flip();
        ByteBuffer body = ByteBuffer.allocate(8);
        body.clear();
        body.putChar('a');
        body.putChar('a');
        body.putChar('a');
        body.putChar('a');
        body.flip();

        ByteBuffer[] bufferArray = { header, body };
        channel.write(bufferArray);

        channel.force(false);
        channel.close();
    }
}
